import { Component, OnInit,ViewChild } from '@angular/core';
import { StorageService } from '../../common/storage.service';
import { Check } from '../../common/check';
import { AccountService } from '../../../app/account/account/account.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Md5 } from 'ts-md5/dist/md5';
import { CropperSettings,ImageCropperComponent } from 'ng2-img-cropper';
import { log } from 'util';


@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css']
})
export class AccountComponent implements OnInit {

  /************************个人资料*****************************/
  personalObj: any = {}; // 提交对象
  nameCheckShow: boolean;
  briefCheckShow: boolean;
  nameTip: any;
  briefTip: any;
  nameTipRight: boolean;
  addressProvinceCodeArr: any[] = []; // 居住市省
  addressCityCodeArr: any[] = []; // 居住市市
  addressDistrictCodeArr: any[] = []; // 居住市区
  userInfoCode: any; // 用户code
  addressObj: any={}; // 居住市
  emailRight: boolean = true; // 邮箱                                                                                          
  /***************************设置头像**************************/
  data: any={};
  cropperSettings: CropperSettings=new CropperSettings();
  imgUrl:string='';
  display1:boolean;
  @ViewChild('cropper', undefined)
  cropper:ImageCropperComponent;
  url:string = (this.service.spaceService.baseUrl || 'http://172.18.8.76/') + 'zuul/com-dyrs-mtsp-fileservice/fileservice/fileDFSSave/api';

  /*****************************修改密码************************/
  submited:boolean;
  title: string = "修改密码";
  objToPost:any = {};
  private check: Check = new Check();
  oldPwdCheckShow: boolean;
  oldPwdTip: string='';
  newPwdCheckShow: boolean;
  newPwdTip: string='';
  conPwdCheckShow: boolean;
  conPwdTip: string='';

  /******************************绑定手机***********************/
  mobile:any;//显示 号码
  originMobile:number;//输入 号码
  newMobile:any;//新号码
  phoneCode:number;//手机验证码
  phoneTip: string = "";
  next:boolean;//是否 下一页 编辑
  change:boolean;//是否 显示弹框
  countdown:number;//验证码 倒计时
  isJump:boolean = true;//是否可用跳转
  isExistMobile:boolean;
  changePhoneMsg:string;
  userTypeCode:string;
  isFucos1:boolean;

  private localStorage = window.localStorage ? window.localStorage : null;
  constructor(private storage:StorageService,private service: AccountService, private route: ActivatedRoute, private router: Router) { 
    this.cropperSettings = new CropperSettings();
    this.cropperSettings.width = 100;
    this.cropperSettings.height = 100;
    this.cropperSettings.croppedWidth = 200;
    this.cropperSettings.croppedHeight = 200;
    this.cropperSettings.cropOnResize = true;
    this.cropperSettings.canvasWidth = 360;
    this.cropperSettings.canvasHeight = 200;
    this.cropperSettings.noFileInput = true;
    this.cropperSettings.fileType ='image/jpg'

    this.data = {};
  }


  ngOnInit() {
    this.chooseProvince(); // 居住
    this.personalObj.sex = 'sex_man';
    this.storage.loading();
    this.storage.getRights().then(data=>{
      this.storage.loadout();

        /************************个人资料*****************************/
        // 根据code获取员工详情
        this.userTypeCode = data.userTypeCode;
        if(this.userTypeCode){
          let code = {
            code: this.userTypeCode
          }
          this.storage.loading();
          this.service.detailById(code).then(data => {
            this.storage.loadout();
            if (data.result) {
              this.personalObj = data.data;
              this.personalObj.sex = data.data.sex;
  
              // 居住地
              if(data.data.addressProvinceCode){
                this.addressObj.addressProvince = {code: data.data.addressProvinceCode,name: data.data.addressProvinceName};
                this.chooseCity(this.addressObj.addressProvince);
                if(data.data.addressCityCode){
                  this.addressObj.addressCity = {code: data.data.addressCityCode,name: data.data.addressCityName};
                  this.chooseDistrict(this.addressObj.addressCity);
                  if(data.data.addressDistrictCode){
                    this.addressObj.addressDistrict = {code: data.data.addressDistrictCode,name: data.data.addressDistrictName};
                  }
                }
              }else{
                this.addressObj.addressProvince = {};
                this.addressObj.addressCity = {};
                this.addressObj.addressDistrict = {};
              }
            }
          });
        }
        /***************************设置头像**************************/


        /*****************************修改密码************************/
        this.objToPost = data.userInfo;
        this.imgUrl = data.userInfo.iconUrl;
        //this.imgUrl = data.userInfo.iconUrl;
        /******************************绑定手机***********************/
        let reg = /^(\d{3})\d{4}(\d{4})$/;
        this.mobile = data.userInfo.mobile.replace(reg, "$1****$2");
      
    })
  }

  /*************************个人资料****************************/
  // 用户名
  userValidate() {
    this.personalObj.fullName = this.personalObj.fullName ? this.personalObj.fullName.trim() : '';
    if(!this.personalObj.fullName){
      this.nameCheckShow = true;
      this.nameTip = '请输入姓名';
      return 
    }else{
      this.nameCheckShow = false;
      this.nameTip = '';
    }
    // this.storage.loading();
    // this.service.nameValidate(this.personalObj).then(data => {
    //   this.storage.loadout();
    //   if (data.result) {
    //     this.nameCheckShow = false;
    //     this.nameTip = '';
    //   } else {
    //     this.nameCheckShow = true;
    //     this.nameTip = data.msg;
    //   }
    // })
  }

  // 居住市省市区
  chooseProvince() {
    this.addressCityCodeArr = [];
    this.addressDistrictCodeArr = [];
    this.addressObj.addressProvince = {code:'',name:''};
    this.addressObj.addressCity = {code:'',name:''};
    this.addressObj.addressDistrict = {code:'',name:''};
    this.service.province().then(data => {
      if (data.result) {
        this.addressProvinceCodeArr = data.data;
        this.addressProvinceCodeArr.unshift({name:'请选择省',code:null});
      } else {
        // this.storage.messageService.emit({ severity: 'error', detail: data.msg })
      }
    })
  }

  chooseCity(data) {
    this.addressDistrictCodeArr = [];
    this.addressObj.addressCity = {code:'',name:''};
    this.addressObj.addressDistrict = {code:'',name:''};
    let provinceCode = {
      code: data.code // 省的code
    }
    this.service.city(provinceCode).then(data => {
      if (data.result) {
        this.addressCityCodeArr = data.data;
        this.addressCityCodeArr.unshift({name:'请选择市',code:null});
      } else {
        // this.storage.messageService.emit({ severity: 'error', detail: data.msg })
      }
    })
  }

  chooseDistrict(data) {
    this.addressDistrictCodeArr = [];
    this.addressObj.addressDistrict = {code:'',name:''};
    let cityCode = {
      code: data.code // 市的code
    }
    this.service.district(cityCode).then(data => {
      if (data.result) {
        this.addressDistrictCodeArr = data.data;
        this.addressDistrictCodeArr.unshift({name:'请选择区/乡/镇',code:null});
      } else {
        // this.storage.messageService.emit({ severity: 'error', detail: data.msg })
      }
    })
  }

  // 个人简介
  briefValidate(){
    this.personalObj.introduction = this.personalObj.introduction ? this.personalObj.introduction.trim() : '';
    if(!this.personalObj.introduction){
      this.briefCheckShow = true;
      this.briefTip = '请输入个人简介';
      return 
    }else{
      this.briefCheckShow = false;
      this.briefTip = '';
    }
  }

  // emailTest
  emailTest(data) {
    let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    if (data) {
      data = data.trim();
      if (!reg.test(data)) {
        this.emailRight = false;
        return;
      } else {
        this.emailRight = true;
      }
    } else {
      this.emailRight = true;
    }
  }

  // 保存
  save(){
    this.validAll();
    if (this.personalObj.mail) {
      if (!this.emailRight) {
        return;
      }
    }
    if(!this.nameCheckShow && !this.briefCheckShow){
      this.storage.loading();
      this.service.updateSaveData(this.personalObj).then(data => {
        this.storage.loadout();
        if (data.result) {
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        }else {
          this.storage.messageService.emit({ severity: 'error', detail: data.msg })
        }
      })
    }
  }

  validAll() {
    this.userValidate();
    this.briefValidate();
    this.emailTest(this.personalObj.mail);
    this.personalObj.addressDetail = this.personalObj.addressDetail ? this.personalObj.addressDetail.trim() : '';
    this.personalObj.specialPlane = this.personalObj.specialPlane ? this.personalObj.specialPlane.trim() : '';
    this.personalObj.weChat = this.personalObj.weChat ? this.personalObj.weChat.trim() : '';
    this.personalObj.mail = this.personalObj.mail ? this.personalObj.mail.trim() : '';
    this.personalObj.addressProvinceCode = this.addressObj.addressProvince ? this.addressObj.addressProvince.code : '';
    this.personalObj.addressProvinceName = this.addressObj.addressProvince ? this.addressObj.addressProvince.name : '';

    this.personalObj.addressCityCode = this.addressObj.addressCity ? this.addressObj.addressCity.code : '';
    this.personalObj.addressCityName = this.addressObj.addressCity ? this.addressObj.addressCity.name : '';

    this.personalObj.addressDistrictCode = this.addressObj.addressDistrict ? this.addressObj.addressDistrict.code : '';
    this.personalObj.addressDistrictName = this.addressObj.addressDistrict ? this.addressObj.addressDistrict.name : '';
  
  }
  /***************************设置头像**************************/
  getBlobBydataURI(dataURI,type) {  
    let binary = atob(dataURI.split(',')[1]);  
    let array = [];  
    for(var i = 0; i < binary.length; i++) {  
        array.push(binary.charCodeAt(i));  
    }  
    return new Blob([new Uint8Array(array)], {type:type });  
  } 

  upLoad(){
      let xhr = new XMLHttpRequest();
      let  $Blob= this.getBlobBydataURI(this.data.image,'image/jpeg');
      let formData = new FormData();    
      formData.append("files", $Blob ,"file_"+ new Date().getTime()+".jpeg");  
      formData.append("id", "23052"); 
      xhr.open('POST', this.url, true);
      xhr.onreadystatechange=()=>{
        if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
          let result = JSON.parse(xhr.response)
          console.log(result);
          if(result.result){
            let filePath=result.data.filePath;
            let iconCode=result.data.fileCode;
            let data= {
              code: this.objToPost.code,
              iconUrl: filePath,
              iconCode: iconCode
            }
            console.log(data);
            this.service.updateIconUrl(data).then(res => {
              if (res.result) {
                //上传成功
                this.imgUrl = filePath;
                this.storage.messageService.emit({severity:'success', detail:'操作成功！'})
                this.storage.userinfoService.emit({iconUrl:filePath})
              } else {
                //提示;
                this.storage.messageService.emit({severity:'error', detail:'操作失败，请重新操作！'})
              }
            });

          }else{
            //
            this.storage.messageService.emit({severity:'error', detail:'操作失败，请重新操作！'})
          }

        }
      }
      xhr.withCredentials = true;
      xhr.send(formData);
    
      return formData 
  }
  fileChangeListener($event) {
     console.log('asdasda')
      var image:any = new Image();
      var file:File = $event.target.files[0];
      var myReader:FileReader = new FileReader();
      var that = this;
      myReader.onloadend = function (loadEvent:any) {
          image.src = loadEvent.target.result;
          that.cropper.setImage(image);
  
      };
  
      myReader.readAsDataURL(file);
  }

  /****************************修改密码*************************/
  //原密码
  oldPwdValidate(){
    if(!this.objToPost.accountPassword || !this.check.password(this.objToPost.accountPassword)){
      this.oldPwdCheckShow = true;
      this.oldPwdTip = '请输入6-12位数字与字母组合';
      return 
    }
  }

  //新密码
  newPwdValidate(){
    if(!this.objToPost.newPwd || !this.check.password(this.objToPost.newPwd)){
      this.newPwdCheckShow = true;
      this.newPwdTip = '请输入6-12位数字与字母组合';
      return 
    }else{
      
      if(this.objToPost.newPwd==this.objToPost.confirmPwd){
        this.conPwdCheckShow = false;
        this.conPwdTip = '';
      }
    }
    
  }

  //再次输入密码
  conPwdValidate(){
    if(!this.objToPost.confirmPwd || !this.check.password(this.objToPost.confirmPwd)){
      this.conPwdCheckShow = true;
      this.conPwdTip = '请输入6-12位数字与字母组合';
      return 
    }else{
        if(this.objToPost.newPwd!=this.objToPost.confirmPwd){
          this.conPwdCheckShow = true;
          this.conPwdTip = '您两次输入的密码不一致，请重新输入';
          return
        }
    }
    
  }

  //修改当前登录人的密码
  updatePwd(){
    this.oldPwdValidate();
    this.newPwdValidate();
    this.conPwdValidate();
    console.log(!this.objToPost.accountPassword)
    if(!this.objToPost.accountPassword || !this.check.password(this.objToPost.accountPassword) || !this.objToPost.newPwd || !this.check.password(this.objToPost.newPwd)|| !this.objToPost.confirmPwd || !this.check.password(this.objToPost.confirmPwd)){
        this.storage.messageService.emit({severity:'error', detail:'请输入6-12位数字与字母组合'})
        return;
    }
    if(this.objToPost.newPwd!=this.objToPost.confirmPwd){
      this.storage.messageService.emit({severity:'error', detail:'您两次输入的密码不一致，请重新输入'})
      return;
    }
    
    let oldPassword = Md5.hashStr(this.objToPost.accountPassword).toString();
    //let editNewPw = Md5.hashStr(this.objToPost.newPwd).toString();
    if(this.objToPost.accountPassword==this.objToPost.newPwd){
      //this.forgotMsg = '新密码与原始密码一致,请重新输入!';
      this.storage.messageService.emit({severity:'error', detail:'新密码不能与原密码相同'})
      return;
    }

    //this.objToPost['']

    let data = {
      accountPassword: oldPassword,
      newPwd: this.objToPost.newPwd,
      code: this.objToPost.code 
    }
    this.service.updatePwd(data).then(data =>{
      let url = this.service.redirectUrl || "saas";
      this.storage.loadout();
      if(data.result){
        this.storage.loadout();
        //this.objToPost=null;
        this.storage.messageService.emit({severity:'success', detail:'修改成功，请重新登录'})
        setTimeout(() => {
          this.loginOut();
        }, 1500);
      }else{
        this.storage.messageService.emit({severity:'error', detail:data.msg})
      }
    })
  }




  /*************************绑定手机****************************/
  //显示弹框
  adapter(b?):void {
     //下一步
     if (!b){
      this.validMobile(1);
      return;
    }
    this.bindMobile(b);

  }

  validMobile(n?):void{
    let params:any = {};
    params.mobile = this.originMobile;
    this.service.validInputMobile(params).then(res => {
      if (res.result) {//验证通过
        this.isJump = true;
        if (n) {
          this.next = true;
        }
      } else {
        this.isJump = false;
      }
    });
  }

  userIsExistsByMobile():void {
    let params:any = {};
    params.mobile = this.newMobile;
    this.service.userIsExistsByMobile(params).then(res => {
      if (!res.result) {
        this.isExistMobile = true;
      } else {
        this.isExistMobile = false;
      }
    });
  }

 //发送手机验证码
  sendMsg():void{
    if (this.isExistMobile) {
      return ;
    }
    let params:any={};
    params.mobile = this.newMobile;

    this.service.sendMsg(params).then(res => {
        if (res.result) {
          this.count();
        } else {

        }
    });

  }

  count():void {
    this.countdown = 60;
    let interval = setInterval(() => {
      this.countdown--;
      if (this.countdown==0) {
        clearInterval(interval);
      }
    },1000)
  }

  bindMobile(b?):void {
    if (this.next) {
      let params:any = {};
      params.mobile = this.newMobile;
      params.phoneCode = this.phoneCode;
      params.code = this.objToPost.code;
      this.service.updateMobile(params).then(res => {

        if (res.result) {
          
          this.storage.messageService.emit({severity:'success', detail:'提交成功，请重新登录'});
          setTimeout(() => {
            this.loginOut();
          }, 1500);
          
          // let reg = /^(\d{3})\d{4}(\d{4})$/;
          // this.mobile = this.newMobile.replace(reg, "$1****$2");
          // this.storage.userinfoService.emit({mobile:this.mobile})

          // this.change = false;
          // this.reset();
        } else {
          if(res.errcode=="1001"){
            this.changePhoneMsg = '2';
            this.isFucos1 = false;
          }else if( res.errcode=="1002"){
            this.changePhoneMsg = '1';
            this.isFucos1 = false;
          }else{
            this.storage.makesureService.emit({
              message: res.msg,
              header: '提示',
              icon: '',
              acceptVisible:false,
              rejectVisible:false,
            })
  
          }
        }
      });

    }
  }

  reset(f?){
    if (f) {
      f.reset()
    }
    setTimeout(() => {
      this.next = false;
      this.isJump = true;
      this.isExistMobile = false;
      this.originMobile = undefined;
      this.newMobile = undefined;  
    }, 100);
  }

  loginOut():void{
    this.router.navigateByUrl('login');
    this.localStorage.removeItem('rights');
    this.localStorage.removeItem('dic');
    this.localStorage.removeItem('channels');
  }
}
